package com.jcli.novel_p;

import java.io.*;
import java.util.*;

public class AddRandomProperties {
    public static void main(String[] args) {
        // 加载现有的 config.properties 文件中的键值对
        Properties properties = loadProperties();

        // 新建一个 Properties 对象
        // Properties properties = new Properties();

        // 生成并添加 100 个随机键值对
        for (int i = 0; i < 100; i++) {
            String key = generateRandomKey();
            String value = generateRandomValue();
            properties.setProperty(key, value);
        }

        // 将新的键值对和现有的键值对一起保存到 config.properties 文件
        saveProperties(properties);
        System.out.println("成功添加 100 个随机键值对到 config.properties 文件。");

       /* try (OutputStream outputStream = new FileOutputStream("src/main/resources/config.properties")) {
            properties.store(outputStream, null);
            System.out.println("成功添加 100 个随机键值对到 config.properties 文件。");
        } catch (IOException e) {
            e.printStackTrace();
        }*/
    }
    private static Properties loadProperties() {
        Properties properties = new Properties();
        try (InputStream inputStream = new FileInputStream("src/main/resources/config.properties")) {
            properties.load(new InputStreamReader(inputStream, "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties;
    }
    private static void saveProperties(Properties properties) {
        try (OutputStream outputStream = new FileOutputStream("src/main/resources/config.properties")) {
            properties.store(outputStream, null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static String generateRandomKey() {
        // 生成一个随机字符串作为键
        Random random = new Random();
        byte[] bytes = new byte[5];
        random.nextBytes(bytes);
        return Base64.getEncoder().encodeToString(bytes);
    }

    private static String generateRandomValue() {
        // 生成一个随机整数作为值
        Random random = new Random();
        int randomValue = random.nextInt(1000);
        return String.valueOf(randomValue);
    }
}
